<template>
    <div class="data-screening">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="盘点单号">
          <el-input
            v-model="filterForm.stockNum"
            placeholder="请输入盘点单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="起始时间">
          <el-date-picker
            v-model="filterForm.startTime"
            type="datetime"
            placeholder="起始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="filterForm.endTime"
            type="datetime"
            placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="filterForm.status"
            style="width: 150px"
            placeholder="请选择"
          >
            <el-option label="等待审核" value="等待审核"></el-option>
            <el-option label="审核成功" value="审核成功"></el-option>
            <el-option label="审核失败" value="审核失败"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary">查询</el-button>
        <el-form-item>
          <el-button type="primary" @click="handleCreate">新增</el-button>
          <el-button @click="handleEdit">编辑</el-button>
          <el-button
            type="danger"
            @click="handleDelete('批量删除')"
            :disabled="selectedRows.length === 0"
            >批量删除</el-button
          >
          <el-button @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
  
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        border
        style="width: 1500px"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="编号" prop="stocktakingModelId"></el-table-column>
        <el-table-column label="盘点单号" prop="stockNum"></el-table-column>
        <el-table-column label="盘点类型" prop="relaCreator"></el-table-column>
        <el-table-column label="关联单号" prop="internalCode"></el-table-column>
        <el-table-column label="状态" prop="relaReviewer"></el-table-column>
        <el-table-column label="制单人" prop="stock"></el-table-column>
        <el-table-column v-slot="scoped" label="创建时间" prop="relaCreationTime">
          {{
            scoped.row.relaCreationTime
              ? scoped.row.relaCreationTime.substring(0, 10)
              : ""
          }}
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="GetStodto(scope.row.internalCode)"
              >查看</el-button
            >
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="
                handleDelete(scope.row.stocktakingModelId, [scope.row.stockNum])
              "
              >删除</el-button
            >
            <el-button type="text" size="small" @click="handleUpload(scope.row)"
              >上传</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="form1.PageIndex"
          v-model:page-size="form1.PageSize"
          :page-sizes="[1, 3, 15, 100]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="form1.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog #default="scope" v-model="dialogVisible" title="盘点单详情">
        <div class="details-container">
          <div class="detail-item">
            <span>编号：</span>
            <span>{{ tableData1.stocktakingModelId }}</span>
          </div>
          <div class="detail-item">
            <span>盘点单号：</span>
            <span>{{ tableData1.stockNum }}</span>
          </div>
          <div class="detail-item">
            <span>单据状态：</span>
            <span>{{ tableData1.relaCreator }}</span>
          </div>
          <div class="detail-item">
            <span>关联单号：</span>
            <span>{{ tableData1.internalCode }}</span>
          </div>
          <div class="detail-item">
            <span>创建人：</span>
            <span>{{ tableData1.stock }}</span>
          </div>
          <div class="detail-item">
            <span>创建时间：</span>
            <span>{{
              scope.row.relaCreationTime
                ? scope.row.relaCreationTime.substring(0, 10)
                : ""
            }}</span>
          </div>
          <div class="detail-item">
            <span>备注：</span>
            <span>{{ tableData1.rember }}</span>
          </div>
          <div class="detail-item">
            <span>审核原因：</span>
            <span>{{ tableData1.relaReviewer }}</span>
          </div>
        </div>
        <el-table :data="tableData2" style="width: 100%">
          <el-table-column
            prop="manufacturerCode"
            label="产品编码"
          ></el-table-column>
          <el-table-column prop="productName" label="产品名称"></el-table-column>
          <el-table-column prop="specification" label="规格"></el-table-column>
          <el-table-column prop="internalCode" label="订单号"></el-table-column>
          <el-table-column prop="currentLocation" label="当前库位"
            >库位A</el-table-column
          >
          <el-table-column prop="lowerLimit" label="数量"></el-table-column>
          <el-table-column prop="upperLimit" label="盘点数"></el-table-column>
          <el-table-column prop="profitLoss" label="盈亏数"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ElMessageBox, ElMessage } from "element-plus";
  import { reactive, onMounted, ref } from "vue";
  import axios from "axios";
  import { useRouter, useRoute } from "vue-router";
  import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
  // 模拟表格数据
  const tableData1 = ref([]);
  const tableData2 = ref([]);
  //明细
  const GetStodto = (internalCode: string) => {
    dialogVisible.value = true;
    KongaUrl
      .get(
        `/wangcong/api/Whouase/GetStodto?InternalCode=${internalCode}`
      )
      .then((res) => {
        tableData1.value = res.data.data[0];
        console.log(tableData1.value);
        // 获取入库单产品信息
        KongaUrl
          .get(
            `/wangcong/api/Whouase/GetPtodto?InternalCode=${internalCode}`
          )
          .then((res) => {
            tableData2.value = res.data.data;
            console.log(tableData2.value);
          });
      });
  };
  
  // 控制对话框显示隐藏
  const dialogVisible = ref(false);
  // 筛选表单数据
  const filterForm = ref({
    stockNum: "",
    startTime: "",
    endTime: "",
    status: "",
  });
  
  // 表格数据
  const tableData = ref([]);
  const form1 = reactive({
    TotalCount: 0,
    PageCount: 0,
    PageSize: 15,
    PageIndex: 1,
  });
  
  onMounted(() => {
    GetSto();
  });
  
  const GetSto = () => {
    KongaUrl
      .get("/wangcong/api/Whouase/GetSto", {
        params: {
          PageSize: form1.PageSize,
          PageIndex: form1.PageIndex,
        },
      })
      .then((res) => {
        tableData.value = res.data.data.list;
        form1.TotalCount = res.data.data.totalCount;
        form1.PageCount = res.data.data.pageCount;
      })
      .catch((error) => {
        ElMessage.error(`获取数据失败: ${error.message}`);
      });
  };
  
  //#region 分页
  const handleSizeChange = (newSize) => {
    form1.PageSize = newSize;
    GetSto();
  };
  
  const handleCurrentChange = (newPage) => {
    form1.PageIndex = newPage;
    GetSto();
  };
  
  // 新增
  const handleCreate = () => {
    console.log("触发新增操作");
  };
  
  // 编辑
  const handleEdit = (row = null) => {
    console.log("触发编辑操作", row);
  };
  
  // 修改选择处理逻辑（确保ID有效性）
  const selectedRows = ref<any[]>([]);
  const handleSelectionChange = (val: any[]) => {
    selectedRows.value = val;
  };
  
  // 优化后的删除方法
  const handleDelete = async (id: any, stockNum: any = []) => {
    try {
      let ids = [];
      let stockNumbers = [];
  
      if (id === "批量删除") {
        // 批量删除逻辑
        if (selectedRows.value.length === 0) {
          ElMessage.warning("请至少选择一条记录");
          return;
        }
        ids = selectedRows.value.map((item) => item.stocktakingModelId);
        stockNumbers = selectedRows.value.map((item) => item.stockNum);
  
        await ElMessageBox.confirm(
          `确定要删除${selectedRows.value.length}条记录？`,
          "警告",
          { type: "warning" }
        );
      } else {
        // 单条删除逻辑
        ids = [id];
        stockNumbers = stockNum;
  
        await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
          type: "warning",
        });
      }
  
      // 统一请求处理
      const params = new URLSearchParams();
      params.append("Table", "StocktakingDetail");
      params.append("TableId", "StocktakingModelsStocktakingModelId");
      ids.forEach((id) => params.append("Ids", id.toString()));
      stockNumbers.forEach((num) => params.append("StockNum", num));
  
      const res = await KongaUrl.delete(
        "/wangcong1/api/WHouase/DeleteSto",
        {
          params: params,
          paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
        }
      );
  
      if (res.data.code === 500) {
        ElMessage.success(res.data.message);
        GetSto();
        if (id === "批量删除") {
          selectedRows.value = []; // 清空选择
        }
      } else {
        ElMessage.error(res.data.message);
      }
    } catch (error) {
      if (error !== "cancel") {
        // 忽略用户取消操作
        ElMessage.error(`操作失败: ${error.message}`);
      }
    }
  };
  
  // 导出
  const handleExport = () => {
    console.log("触发导出操作");
  };
  </script>
  
  <style scoped>
  .data-screening {
    padding: 20px;
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .filter-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .filter-form .el-form-item {
    margin-bottom: 0;
  }
  
  .filter-form .form-actions {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
  }
  
  .el-table__header th {
    text-align: center;
    background-color: #409eff;
    color: white;
    font-weight: 500;
    padding: 12px 0;
  }
  
  .el-table__body td {
    text-align: center;
    border-bottom: 1px solid #ebeef5;
    padding: 10px 0;
  }
  
  .el-table__body tr:hover {
    background-color: #f0f5ff;
  }
  
  .el-table__body .el-button {
    transition: color 0.3s;
  }
  
  .el-table__body .el-button:hover {
    color: #409eff;
  }
  
  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
  .details-container {
    border-bottom: 1px solid #e4e7ed;
    padding: 10px 0;
  }
  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .detail-item span {
    margin-right: 10px;
  }
  .el-dialog {
    border: 1px solid #ccc;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  /* 信息展示容器 */
  .details-container {
    border-bottom: 1px solid #e4e7ed;
    padding: 10px 15px;
  }
  /* 每个信息项 */
  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  /* 信息项的标签 */
  .detail-item span:first-child {
    width: 80px;
    color: #666;
  }
  /* 信息项的值 */
  .detail-item span:last-child {
    color: #333;
  }
  /* 表格样式 */
  .el-table {
    border: 1px solid #e4e7ed;
    border-top: none;
  }
  /* 表格表头 */
  .el-table__header {
    background-color: #f4f4f5;
  }
  .el-table__header th {
    border-right: 1px solid #e4e7ed;
    color: #666;
    font-weight: 500;
    padding: 10px 15px;
    text-align: center;
  }
  /* 表格行 */
  .el-table__body tr {
    border-bottom: 1px solid #e4e7ed;
  }
  .el-table__body td {
    border-right: 1px solid #e4e7ed;
    color: #333;
    padding: 10px 15px;
    text-align: center;
  }
  </style>